package org.whuims.web.util;

import org.elasticsearch.common.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import org.whuims.entity.Paragraph;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhongwei on 2017/6/16.
 */
@Component
public class ParagraphExtractor {

    public List<Paragraph> extractPdf(String xmlText, long documentId) {
        Document document = Jsoup.parse(xmlText);
        List<Element> pages = document.getElementsByTag("page");
        List<Paragraph> paragraphs = new ArrayList<Paragraph>();
        for (Element element : pages) {
            Paragraph paragraph = new Paragraph();
            String textContent = element.text();
            if (Strings.isNullOrEmpty(textContent) || textContent.length() < 5)
                continue;
            paragraph.setContent(textContent);
            String orderStr = element.attr("number");
            String heightStr = element.attr("height");
            String widthStr = element.attr("width");
            int orderInDoc = Integer.parseInt(orderStr);
            Float height = Float.parseFloat(heightStr);
            Float width = Float.parseFloat(widthStr);
            paragraph.setOrderInDocument(orderInDoc);
            paragraph.setHeight(height);
            paragraph.setWidth(width);
            paragraph.setDocumentId(documentId);
            paragraphs.add(paragraph);
        }
        return paragraphs;
    }

    public List<Paragraph> extractWord(String content, long documentId) {
        String[] arr = content.split("\n");
        List<Paragraph> paragraphs = new ArrayList<Paragraph>();
        int pCounter = 1;
        for (String str : arr) {
            if (Strings.isNullOrEmpty(str) || str.length() < 5)
                continue;
            Paragraph paragraph = new Paragraph();
            paragraph.setContent(str);
            paragraph.setOrderInDocument(pCounter++);
            paragraph.setDocumentId(documentId);
            paragraphs.add(paragraph);
        }
        return paragraphs;
    }
}
